<template>
	<view class="auth">
		<view class="title">ugo-登录</view>
		
		<!-- 通过设置button的open-type="chooseAvatar"就可以直接唤起 修改头像的弹层。 -->
		
		<button class="loginBtnAvatar" open-type="chooseAvatar" @chooseavatar="hChooseAvatar">
			<image class="avatar" :src="avatarUrl"></image>
		</button>
		
		<view>
			<input type="nickname" placeholder="点击修改昵称" v-model="nickName"/>
		</view>
		<button class="loginBtn" size="mini"  @click="hLogin" type="primary">
			登录
		</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				avatarUrl: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
				nickName: ''
			}
		},
		async onLoad() {
			// 1. 拿到code
			const res = await uni.login()
			console.log(res)
			this.code = res.code
		},
		methods: {
			hChooseAvatar(e){
				console.log(e)
				// 更新avatarUrl
				this.avatarUrl = e.detail.avatarUrl
			},
			async hLogin(user) {
				// 2. 调用 wx.getUserInfo
				const { iv, signature, rawData, encryptedData} = await uni.getUserInfo()
				// 3. 调用自己服务器的接口， 传入前面两步的参数
				const {data} = await this.request({
					url: '/users/wxlogin',
					method: 'post',
					data: {
						iv,
						signature,
						rawData,
						encryptedData,
						code: this.code
					}
				})
				
				console.log(data.token)
				// 保存token
				uni.setStorageSync('token', data.token)
				// 页面后退
				uni.navigateBack()
			}
		}
	}
</script>

<style lang="scss">
.auth {
	
	padding:50rpx;
	text-align: center;
	.title{
		margin: 40rpx auto;
	}
	.loginBtnAvatar {
		width: 200rpx;
		height: 200rpx;
		border-radius: 50%;
		padding:0px;
		margin: 40rpx auto;
	}
	.avatar {
		width: 200rpx;
		height: 200rpx;
		border-radius: 50%;
		border: 2rpx solid #fff;
	}

	.nickname {
		display: block;
		text-align: center;
		margin-top: 20rpx;
		font-size: 30rpx;
		color: #fff;
	}
	.loginBtn {
		width: 200rpx;
		margin: 50rpx auto;
		display: block;
	}
}
</style>